package controller

import (
	myConfig "common/config"
	"common/helper"
	myredis "common/redis"
	myUserHelp "common/userHelp"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/valyala/fasthttp"
	"member/model"
	"time"
)

//玩家周返回相关

type WeekReturn struct {
	DeposiReturn       float64 `json:"week_deposit_return" db:"week_deposit_return" cbor:"week_deposit_return"`
	BetReturn          float64 `json:"week_bet_return" db:"week_bet_return" cbor:"week_bet_return"`
	LostReturn         float64 `json:"week_lost_return" db:"week_lost_return" cbor:"week_lost_return"`
	Proxy_commi_return float64 `json:"week_proxy_commi_return" db:"week_proxy_commi_return" cbor:"week_proxy_commi_return"`
	DailyBetReturn     float64 `json:"day_bet_return" db:"daily_bet_return" cbor:"day_bet_return"`
}

func GetWeekReturnFromDB(valUid string) (WeekReturn, bool) {
	var tWeekReturn WeekReturn
	sqlSelect := fmt.Sprintf("select week_deposit_return,week_bet_return,week_lost_return,week_proxy_commi_return from tbl_member_return where uid=%s", valUid)
	rows, err := model.GetSlaveDBInstance().Query(sqlSelect)
	if err != nil {
		helper.GetloggerInstance().Criticalf("%s\n%s", sqlSelect, err.Error())
		return tWeekReturn, false
	}

	for rows.Next() {
		rows.Scan(&tWeekReturn.DeposiReturn, &tWeekReturn.BetReturn, &tWeekReturn.LostReturn, &tWeekReturn.Proxy_commi_return)
	}

	return tWeekReturn, true
}

/*
查询周亏损相关
*/

type WeekLostReturnItem struct {
	WeekLostReturn float64 `json:"WeekLostReturn" db:"WeekLostReturn" cbor:"WeekLostReturn"`
	Running        float64 `json:"Running" db:"Running" cbor:"Running"`
}

func (that MemberController) QueryWeeklostReturn(ctx *fasthttp.RequestCtx) {
	valUid := model.GetUidFromToken(ctx)

	now := time.Now()
	daysUntilMonday := int(now.Weekday() - time.Monday)
	if daysUntilMonday < 0 {
		daysUntilMonday += 7
	}

	var tReturnItem WeekLostReturnItem
	tWeekReturn, _ := GetWeekReturnFromDB(valUid)
	tReturnItem.WeekLostReturn = tWeekReturn.LostReturn

	// 周一的时间
	monday := now.AddDate(0, 0, -daysUntilMonday)
	lastWeekMonday := monday.AddDate(0, 0, -7)

	//查询上周总投注
	sqlSelect := fmt.Sprintf("select IFNULL(sum(valid_waged),0)  from tbl_report_user_daily where uid=%s and  created_at>='%s' and created_at<'%s'",
		valUid, lastWeekMonday.Format("2006-01-02"), monday.Format("2006-01-02"))

	model.GetSlaveDBInstance().Get(&tReturnItem.Running, sqlSelect)

	helper.Print(ctx, true, tReturnItem)
}

/*
领取周亏损
*/
func (that MemberController) AchieveWeeklostReturn(ctx *fasthttp.RequestCtx) {
	valUid := model.GetUidFromToken(ctx)
	if valUid == "" {
		helper.Print(ctx, false, errors.New(helper.AccessTokenExpires))
		return
	}

	lockKey := valUid + "lostReturn"
	if !myredis.Lock(model.GetRedisInstance(), lockKey) {
		helper.GetloggerInstance().Criticalf("lockError:%s", lockKey)
		return
	}

	defer myredis.Unlock(model.GetRedisInstance(), lockKey)

	var weekLostReturn float64
	sqlSelect := fmt.Sprintf("select week_lost_return from tbl_member_return where uid=%s", valUid)
	model.GetMasterDBInstance().Get(&weekLostReturn, sqlSelect)

	if weekLostReturn == 0.0 {
		helper.Print(ctx, true, weekLostReturn)
		return
	}

	sqlUpdate := fmt.Sprintf("update tbl_member_return set  week_lost_return = 0.0 where uid=%s", valUid)
	model.GetMasterDBInstance().Exec(sqlUpdate)

	myUserHelp.AddBalanceTransactionRecord(valUid, weekLostReturn, helper.TransactionWeekLostReturn, "0", helper.GenId(), 0.00, "", "", 0)
	myUserHelp.AddUserWageItem(valUid, weekLostReturn, helper.TransactionWeekLostReturn)
	myUserHelp.AddTotalWeekLostReturn(valUid, weekLostReturn)
	if weekLostReturn > 0.0 {
		_, errExec := model.GetMasterDBInstance().Exec("CALL tbl_report_user_change_update(?,?,?,?)", valUid, helper.TransactionWeekLostReturn, weekLostReturn, time.Now().Unix())
		if errExec != nil {
			helper.GetloggerInstance().Emergencyf("CALL tbl_report_user_change_update(%s,%d,%0.2f,%d);	reason:%s",
				valUid, helper.TransactionWeekLostReturn, weekLostReturn, time.Now().Unix(), errExec.Error())
		}
	}
	myUserHelp.AddUserBalanceByFloat64(valUid, weekLostReturn)
	helper.Print(ctx, true, weekLostReturn)
}

/*
查询周充值返还
*/

type WeekDepositReturn struct {
	LastWeekDeposit   float64 `json:"LastWeekDeposit" db:"LastWeekDeposit" cbor:"LastWeekDeposit"`       //上周充值额度
	ThisWeekDeposit   float64 `json:"ThisWeekDeposit" db:"ThisWeekDeposit" cbor:"ThisWeekDeposit"`       //本周充值额度
	WeekDepositReturn float64 `json:"WeekDepositReturn" db:"WeekDepositReturn" cbor:"WeekDepositReturn"` //可领取的周充值返还
}

func (that MemberController) QueryAllReturn(ctx *fasthttp.RequestCtx) {
	valUid := model.GetUidFromToken(ctx)
	tWeekReturn, _ := GetWeekReturnFromDB(valUid)

	//为兼容前面的版本 如果没有daily_bet_return字段 其他数据正常
	var DailyRunningReturn float64
	sqlSelect := fmt.Sprintf("select daily_bet_return from tbl_member_return where uid=%s", valUid)
	selectErr := model.GetMasterDBInstance().Get(&DailyRunningReturn, sqlSelect)

	tWeekReturn.DailyBetReturn = DailyRunningReturn
	if selectErr != nil {
		helper.InfoLog("[QueryAllReturn]:%s error:%s", sqlSelect, selectErr.Error())
	}

	helper.Print(ctx, true, tWeekReturn)
}

func (that MemberController) QueryWeekDepositReturn(ctx *fasthttp.RequestCtx) {
	valUid := model.GetUidFromToken(ctx)

	now := time.Now()
	daysUntilMonday := int(now.Weekday() - time.Monday)
	if daysUntilMonday < 0 {
		daysUntilMonday += 7
	}

	// 周一的时间
	monday := now.AddDate(0, 0, -daysUntilMonday)
	lastWeekMonday := monday.AddDate(0, 0, -7)

	//查询本周与上周总充值
	sqlSelect := fmt.Sprintf("select IFNULL(SUM(amount), 0) from tbl_deposit where uid=%s and (state=362 or state=365) and created_at>=%d",
		valUid, monday.Unix())

	var tReturnItem WeekDepositReturn
	err := model.GetSlaveDBInstance().Get(&tReturnItem.ThisWeekDeposit, sqlSelect)
	if err != nil {
		helper.InfoLog("[QueryWeekDepositReturn:ThisWeekDeposit]sqlSelect: %s error:%s", sqlSelect, err.Error())
	}

	sqlSelect = fmt.Sprintf("select IFNULL(SUM(amount), 0) from tbl_deposit where uid=%s and  (state=362 or state=365) and created_at>=%d and created_at<%d ",
		valUid, lastWeekMonday.Unix(), monday.Unix())
	err = model.GetSlaveDBInstance().Get(&tReturnItem.LastWeekDeposit, sqlSelect)
	if err != nil {
		helper.InfoLog("[QueryWeekDepositReturn:LastWeekDeposit]sqlSelect: %s error:%s", sqlSelect, err.Error())
	}

	sqlSelect = fmt.Sprintf("select week_deposit_return from tbl_member_return where uid=%s", valUid)
	err = model.GetSlaveDBInstance().Get(&tReturnItem.WeekDepositReturn, sqlSelect)
	if err != nil {
		helper.InfoLog("[QueryWeekDepositReturn:WeekDepositReturn]sqlSelect: %s error:%s", sqlSelect, err.Error())
	}
	helper.Print(ctx, true, tReturnItem)
}

/*
查询上周充值记录
*/
type DepositRecordItem struct {
	Oid        string  `json:"oid" db:"oid" cbor:"oid"`
	Amount     float64 `json:"amount" db:"amount" cbor:"amount"`
	CreateTime int32   `json:"created_at" db:"created_at" cbor:"created_at"`
}

func (that MemberController) QueryLastWeekDepositRecord(ctx *fasthttp.RequestCtx) {
	valUid := model.GetUidFromToken(ctx)

	now := time.Now()
	daysUntilMonday := int(now.Weekday() - time.Monday)
	if daysUntilMonday < 0 {
		daysUntilMonday += 7
	}

	// 周一的时间
	monday := now.AddDate(0, 0, -daysUntilMonday)
	lastWeekMonday := monday.AddDate(0, 0, -7)

	var DepositRecord []DepositRecordItem
	sqlSelect := fmt.Sprintf("select id as oid,amount,created_at from tbl_deposit where uid=%s and  (state=362 or state=365) and created_at>=%d and created_at<%d",
		valUid, lastWeekMonday.Unix(), monday.Unix())
	err := model.GetSlaveDBInstance().Select(&DepositRecord, sqlSelect)

	if err != nil {
		helper.InfoLog("[QueryLastWeekDepositRecord:DepositRecord]sqlSelect: %s error:%s", sqlSelect, err.Error())
	}

	helper.Print(ctx, true, DepositRecord)
}

func (that MemberController) QueryThisWeekDepositRecord(ctx *fasthttp.RequestCtx) {
	valUid := model.GetUidFromToken(ctx)

	now := time.Now()
	daysUntilMonday := int(now.Weekday() - time.Monday)
	if daysUntilMonday < 0 {
		daysUntilMonday += 7
	}

	monday := now.AddDate(0, 0, -daysUntilMonday)
	var DepositRecord []DepositRecordItem
	sqlSelect := fmt.Sprintf("select id as oid,amount,created_at from tbl_deposit where uid=%s and  (state=362 or state=365) and created_at>=%d",
		valUid, monday.Unix())
	err := model.GetSlaveDBInstance().Select(&DepositRecord, sqlSelect)
	if err != nil {
		helper.InfoLog("[QueryThisWeekDepositRecord:DepositRecord]sqlSelect: %s error:%s", sqlSelect, err.Error())
	}

	helper.Print(ctx, true, DepositRecord)
}

/*
领取玩家周充值返还
*/

/*
领取周返还
*/
func (that MemberController) AchieveWeekDepositReturn(ctx *fasthttp.RequestCtx) {
	valUid := model.GetUidFromToken(ctx)
	if valUid == "" {
		helper.Print(ctx, false, errors.New(helper.AccessTokenExpires))
		return
	}

	lockKey := valUid + "DepositReturn"
	if !myredis.Lock(model.GetRedisInstance(), lockKey) {
		helper.GetloggerInstance().Criticalf("lockError:%s", lockKey)
		return
	}

	defer myredis.Unlock(model.GetRedisInstance(), lockKey)

	var fWeekDepositReturn float64
	sqlSelect := fmt.Sprintf("select week_deposit_return from tbl_member_return where uid=%s", valUid)
	err := model.GetMasterDBInstance().Get(&fWeekDepositReturn, sqlSelect)

	if err != nil {
		helper.InfoLog("[AchieveWeekDepositReturn:fWeekDepositReturn]sqlSelect: %s error:%s", sqlSelect, err.Error())
	}

	if fWeekDepositReturn == 0.0 {
		helper.Print(ctx, true, fWeekDepositReturn)
		return
	}

	sqlUpdate := fmt.Sprintf("update tbl_member_return set  week_deposit_return = 0.0 where uid=%s", valUid)
	_, err = model.GetMasterDBInstance().Exec(sqlUpdate)

	if err != nil {
		helper.InfoLog("[AchieveWeekDepositReturn:exec]sqlUpdate: %s error:%s", sqlUpdate, err.Error())
	}

	myUserHelp.AddBalanceTransactionRecord(valUid, fWeekDepositReturn, helper.TransactionWeekDepositReturn, "0", helper.GenId(), 0.00, "", "", 0)
	myUserHelp.AddUserWageItem(valUid, fWeekDepositReturn, helper.TransactionWeekDepositReturn)
	myUserHelp.AddTotalWeekDepositReturn(valUid, fWeekDepositReturn)
	if fWeekDepositReturn > 0.0 {
		_, errExec := model.GetMasterDBInstance().Exec("CALL tbl_report_user_change_update(?,?,?,?)", valUid, helper.TransactionWeekDepositReturn, fWeekDepositReturn, time.Now().Unix())
		if errExec != nil {
			helper.GetloggerInstance().Emergencyf("CALL tbl_report_user_change_update(%s,%d,%0.2f,%d);	reason:%s",
				valUid, helper.TransactionWeekDepositReturn, fWeekDepositReturn, time.Now().Unix(), errExec.Error())
		}
	}
	myUserHelp.AddUserBalanceByFloat64(valUid, fWeekDepositReturn)
	helper.Print(ctx, true, fWeekDepositReturn)
}

type applyDepositParam struct {
	State int `json:"state"` //梯度
}

func (that MemberController) GetAppDownloadBonus(ctx *fasthttp.RequestCtx) {
	valUid := model.GetUidFromToken(ctx)
	if valUid == "" {
		helper.Print(ctx, false, helper.AccessTokenExpires)
		return
	}

	lk := fmt.Sprintf("w:%s", myUserHelp.GetMemberName(valUid))
	err := model.WithLock(lk)
	if err != nil {
		return
	}

	defer model.Unlock(lk)

	if myUserHelp.IsGetAppBonus(valUid) {
		helper.Print(ctx, false, helper.AppBonusAlreadyGet)
		return
	}

	bonus := myConfig.GetGameCfgFloat64(myConfig.CfgAppDownloadBonus)
	myUserHelp.AddBalanceTransactionRecord(valUid, bonus, helper.TransactionDownloadAppBonus, "0", helper.GenId(), 0.00, "", "", 0)
	myUserHelp.AddUserWageItem(valUid, bonus, helper.TransactionDownloadAppBonus)
	myUserHelp.AddUserBalanceByFloat64(valUid, bonus)
	myUserHelp.SetAppBonusStatus(valUid, 1)

	if bonus > 0.0 {
		_, errExec := model.GetMasterDBInstance().Exec("CALL tbl_report_user_change_update(?,?,?,?)", valUid, helper.TransactionDownloadAppBonus, bonus, time.Now().Unix())
		if errExec != nil {
			helper.GetloggerInstance().Emergencyf("CALL tbl_report_user_change_update(%s,%d,%0.2f,%d);	reason:%s",
				valUid, helper.TransactionDownloadAppBonus, bonus, time.Now().Unix(), errExec.Error())
		}
	}

	helper.Print(ctx, true, bonus)
}

/*
玩家累计充值梯度奖励
*/
func (that MemberController) AchieveAccuDepositBonus(ctx *fasthttp.RequestCtx) {
	param := applyDepositParam{}
	data := ctx.PostBody()
	err := json.Unmarshal(data, &param)
	if err != nil {
		helper.Print(ctx, false, helper.ParamErr)
		return
	}

	if myConfig.IsActiveOpen(myConfig.ActiveType_Accu_Deposit_Bonus) == 0 {
		helper.Print(ctx, false, helper.AppActiveClose)
		return
	}

	valUid := model.GetUidFromToken(ctx)
	if valUid == "" {
		helper.Print(ctx, false, helper.AccessTokenExpires)
		return
	}

	lk := fmt.Sprintf("w:%s", myUserHelp.GetMemberName(valUid))
	err = model.WithLock(lk)
	if err != nil {
		return
	}

	defer model.Unlock(lk)

	totalDeposit := myUserHelp.GetTotalDeposit(valUid)
	imemMaxStage := myConfig.GetBonusMaxLevelByAccuDeposit(totalDeposit)
	if imemMaxStage == 0 {
		helper.Print(ctx, false, helper.NoAwardCollect)
		return
	}

	bonusStage := myUserHelp.GetDepoistBonusStage(valUid)
	var applyAmount float64
	if param.State == 0 {
		for index := 1; index <= imemMaxStage; index++ {
			if ((1 << (index - 1)) & bonusStage) != 0 {
				continue
			}

			bonus := myConfig.GetBonusByStage(index)
			nAccuDGBStatus := (1 << (index - 1))
			myUserHelp.AddBalanceTransactionRecord(valUid, bonus, helper.TransactionAccuDepositBonus, "0", helper.GenId(), 0.00, "", "", 0)
			myUserHelp.AddUserWageItem(valUid, bonus, helper.TransactionAccuDepositBonus)
			myUserHelp.AddUserBalanceByFloat64(valUid, bonus)
			//myUserHelp.AddDepoistBonusStage(valUid, int64(nAccuDGBStatus))

			oldAccuDGBStatus := myUserHelp.GetDepoistBonusStage(valUid)
			lastAccuDGBStatus := oldAccuDGBStatus | (int64(nAccuDGBStatus))
			myUserHelp.SetDepoistBonusStage(valUid, lastAccuDGBStatus)

			myUserHelp.AddTotalAccuDepositBonus(valUid, bonus)

			applyAmount += bonus
		}
	} else if param.State > 0 && param.State <= imemMaxStage {
		if ((1 << (param.State - 1)) & bonusStage) != 0 {
			helper.Print(ctx, false, helper.NoAwardCollect)
			return
		}

		bonus := myConfig.GetBonusByStage(param.State)
		nAccuDGBStatus := (1 << (param.State - 1))
		myUserHelp.AddBalanceTransactionRecord(valUid, bonus, helper.TransactionAccuDepositBonus, "0", helper.GenId(), 0.00, "", "", 0)
		myUserHelp.AddUserWageItem(valUid, bonus, helper.TransactionAccuDepositBonus)
		myUserHelp.AddUserBalanceByFloat64(valUid, bonus)

		oldAccuDGBStatus := myUserHelp.GetDepoistBonusStage(valUid)
		lastAccuDGBStatus := oldAccuDGBStatus | (int64(nAccuDGBStatus))
		myUserHelp.SetDepoistBonusStage(valUid, lastAccuDGBStatus)
		myUserHelp.AddTotalAccuDepositBonus(valUid, bonus)
		applyAmount = bonus
	}

	if applyAmount > 0.0 {
		_, errExec := model.GetMasterDBInstance().Exec("CALL tbl_report_user_change_update(?,?,?,?)", valUid, helper.TransactionAccuDepositBonus, applyAmount, time.Now().Unix())
		if errExec != nil {
			helper.GetloggerInstance().Emergencyf("CALL tbl_report_user_change_update(%s,%d,%0.2f,%d);	reason:%s",
				valUid, helper.TransactionAccuDepositBonus, applyAmount, time.Now().Unix(), errExec.Error())
		}
	}

	helper.Print(ctx, true, applyAmount)
}

type TotalDeposit struct {
	DepositAmount float64                            `json:"deposit_amount"`
	State         int64                              `json:"state"`
	Item          []myConfig.CfgAccuDepositBonusItem `json:"item"`
}

/*
累计充值奖励
*/
func (that MemberController) TotalDeposit(ctx *fasthttp.RequestCtx) {
	var data TotalDeposit
	var totalDeposit float64
	var state int64
	uid := model.GetUidFromToken(ctx)
	if uid != "" {
		totalDeposit = myUserHelp.GetTotalDeposit(uid)
		state = myUserHelp.GetDepoistBonusStage(uid)
	}

	var cfg myConfig.CsAccuDepositBonusCfg
	s := cfg.GetCfg()
	data.DepositAmount = totalDeposit
	data.State = state
	data.Item = s
	helper.Print(ctx, true, data)
}

/*周投注相关*/

type WeekRunningReturnItem struct {
	WeekRunningReturn float64 `json:"WeekRunningReturn" db:"WeekRunningReturn" cbor:"WeekRunningReturn"`
	ThisWeekRunning   float64 `json:"ThisWeekRunning" db:"ThisWeekRunning" cbor:"ThisWeekRunning"`
	LastWeekRunning   float64 `json:"LastWeekRunning" db:"LastWeekRunning" cbor:"LastWeekRunning"`
}

func (that MemberController) QueryWeekRunningReturn(ctx *fasthttp.RequestCtx) {
	valUid := model.GetUidFromToken(ctx)

	now := time.Now()
	daysUntilMonday := int(now.Weekday() - time.Monday)
	if daysUntilMonday < 0 {
		daysUntilMonday += 7
	}

	var tReturnItem WeekRunningReturnItem
	tWeekReturn, _ := GetWeekReturnFromDB(valUid)
	tReturnItem.WeekRunningReturn = tWeekReturn.BetReturn

	// 周一的时间
	monday := now.AddDate(0, 0, -daysUntilMonday)
	lastWeekMonday := monday.AddDate(0, 0, -7)

	//查询上周总投注
	sqlSelect := fmt.Sprintf("select IFNULL(sum(valid_waged),0)  from tbl_report_user_daily where uid=%s and  created_at>='%s' and created_at<'%s'",
		valUid, lastWeekMonday.Format("2006-01-02"), monday.Format("2006-01-02"))

	model.GetSlaveDBInstance().Get(&tReturnItem.LastWeekRunning, sqlSelect)

	//查询本周总投注
	sqlSelect = fmt.Sprintf("select IFNULL(sum(valid_waged),0)  from tbl_report_user_daily where uid=%s and  created_at>='%s'",
		valUid, monday.Format("2006-01-02"))

	model.GetSlaveDBInstance().Get(&tReturnItem.ThisWeekRunning, sqlSelect)

	helper.Print(ctx, true, tReturnItem)
}

func (that MemberController) AchieveWeekRunningReturn(ctx *fasthttp.RequestCtx) {
	valUid := model.GetUidFromToken(ctx)
	if valUid == "" {
		helper.Print(ctx, false, errors.New(helper.AccessTokenExpires))
		return
	}

	myredis.Lock(model.GetRedisInstance(), valUid+"RunningReturn")

	var fRunningReturn float64
	sqlSelect := fmt.Sprintf("select week_bet_return from tbl_member_return where uid=%s", valUid)
	model.GetMasterDBInstance().Get(&fRunningReturn, sqlSelect)

	if fRunningReturn == 0.0 {
		helper.Print(ctx, true, fRunningReturn)
		myredis.Unlock(model.GetRedisInstance(), valUid+"RunningReturn")
		return
	}

	//增加打码
	sqlUpdate := fmt.Sprintf("update tbl_member_return set  week_bet_return = 0.0 where uid=%s", valUid)
	model.GetMasterDBInstance().Exec(sqlUpdate)
	myUserHelp.AddBalanceTransactionRecord(valUid, fRunningReturn, helper.TransactionWeekBetReturn, "0", helper.GenId(), 0.00, "", "", 0)
	myUserHelp.AddUserWageItem(valUid, fRunningReturn, helper.TransactionWeekBetReturn)
	myUserHelp.AddTotalWeekBetReturn(valUid, fRunningReturn)
	if fRunningReturn > 0.0 {
		_, errExec := model.GetMasterDBInstance().Exec("CALL tbl_report_user_change_update(?,?,?,?)", valUid, helper.TransactionWeekBetReturn, fRunningReturn, time.Now().Unix())
		if errExec != nil {
			helper.GetloggerInstance().Emergencyf("CALL tbl_report_user_change_update(%s,%d,%0.2f,%d);	reason:%s",
				valUid, helper.TransactionWeekBetReturn, fRunningReturn, time.Now().Unix(), errExec.Error())
		}
	}
	myUserHelp.AddUserBalanceByFloat64(valUid, fRunningReturn)
	myredis.Unlock(model.GetRedisInstance(), valUid+"RunningReturn")
	helper.Print(ctx, true, fRunningReturn)
}

/*
查询本周记录
*/

type RunningRecordItem struct {
	SlotRunning   string `json:"slots_running" db:"slots_running" cbor:"slots_running"`
	PesRunning    string `json:"pes_running" db:"pes_running" cbor:"pes_running"`
	CasRunning    string `json:"cas_running" db:"cas_running" cbor:"cas_running"`
	BingoRunning  string `json:"bingo_running" db:"bingo_running" cbor:"bingo_running"`
	JogoRunning   string `json:"jogo_running" db:"jogo_running" cbor:"jogo_running"`
	EsportRunning string `json:"esport_running" db:"esport_running" cbor:"esport_running"`
}

func (that MemberController) QueryThisWeekRunningRecord(ctx *fasthttp.RequestCtx) {
	valUid := model.GetUidFromToken(ctx)

	now := time.Now()
	daysUntilMonday := int(now.Weekday() - time.Monday)
	if daysUntilMonday < 0 {
		daysUntilMonday += 7
	}

	monday := now.AddDate(0, 0, -daysUntilMonday)
	var RunningRecord []RunningRecordItem
	sqlSelect := fmt.Sprintf("select IFNULL(sum(slots_running),0) as slots_running,"+
		"IFNULL(sum(pes_running),0) as pes_running,"+
		"IFNULL(sum(cas_running),0) as cas_running, "+
		"IFNULL(sum(bingo_running),0) as bingo_running,"+
		"IFNULL(sum(jogo_running),0) as jogo_running,"+
		"IFNULL(sum(esport_running),0) as  esport_running  "+
		"from tbl_report_user_daily where uid=%s and created_at>='%s'",
		valUid, monday.Format("2006-01-02"))
	model.GetSlaveDBInstance().Select(&RunningRecord, sqlSelect)

	helper.Print(ctx, true, RunningRecord)
}

func (that MemberController) QueryLastWeekRunningRecord(ctx *fasthttp.RequestCtx) {
	valUid := model.GetUidFromToken(ctx)

	now := time.Now()
	daysUntilMonday := int(now.Weekday() - time.Monday)
	if daysUntilMonday < 0 {
		daysUntilMonday += 7
	}

	monday := now.AddDate(0, 0, -daysUntilMonday)
	lastWeekMonday := monday.AddDate(0, 0, -7)
	var RunningRecord []RunningRecordItem
	sqlSelect := fmt.Sprintf("select IFNULL(sum(slots_running),0) as slots_running,"+
		"IFNULL(sum(pes_running),0) as pes_running,"+
		"IFNULL(sum(cas_running),0) as cas_running, "+
		"IFNULL(sum(bingo_running),0) as bingo_running,"+
		"IFNULL(sum(jogo_running),0) as jogo_running,"+
		"IFNULL(sum(esport_running),0) as  esport_running  "+
		"from tbl_report_user_daily where uid=%s and created_at>='%s' and created_at<'%s'",
		valUid, lastWeekMonday.Format("2006-01-02"), monday.Format("2006-01-02"))
	model.GetSlaveDBInstance().Select(&RunningRecord, sqlSelect)

	helper.Print(ctx, true, RunningRecord)
}
